import { ChangeEvent, FC, useRef, useState } from "react";
import styles from "./EditHeader.module.scss";
import { Button, Typography, Space, Input, message } from "antd";
import { EditOutlined, LeftOutlined } from "@ant-design/icons";
import { useNavigate, useParams } from "react-router-dom";
import EditToolBar from "./EditToolBar";
import useGetPageInfo from "@/hooks/useGetPageInfo";
import { useDispatch } from "react-redux";
import { changeTitle } from "@/store/pageInfoReducer";
import useGetComponentInfo from "@/hooks/useGetComponentInfo";
import { useDebounceEffect, useKeyPress, useRequest } from "ahooks";
import { updateQuestionService } from "@/services/question";

const { Title } = Typography;

const TitleElement: FC = () => {
  const { title } = useGetPageInfo();
  const dispatch = useDispatch();
  const [editState, setEditState] = useState(false);

  const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
    const newTitle = e.target.value;
    if (!newTitle) return;
    dispatch(changeTitle(newTitle));
  };

  if (editState) {
    return (
      <Input
        value={title}
        onChange={handleChange}
        onPressEnter={() => setEditState(false)}
        onBlur={() => setEditState(false)}
      />
    );
  }

  return (
    <Space>
      <Title level={4} style={{ marginBottom: 0, lineHeight: 1 }}>
        {title}
      </Title>
      <Button
        icon={<EditOutlined />}
        type="text"
        onClick={() => setEditState(true)}
      ></Button>
    </Space>
  );
};

// 保存 componentList + pageInfo
const SaveButton: FC = () => {
  const { componentList } = useGetComponentInfo();
  const pageInfo = useGetPageInfo();
  const { id } = useParams();
  const isHandSave = useRef(false);

  const { loading, run: save } = useRequest(
    async () => {
      if (!id) return;
      await updateQuestionService(id, { ...pageInfo, componentList });
    },
    {
      manual: true,
      onSuccess() {
        if (isHandSave.current) {
          message.success("保存成功");
        }
      },
    }
  );

  const saveInfo = () => {
    isHandSave.current = true;
    save();
  };

  useKeyPress(["ctrl.s", "meta.s"], (e: KeyboardEvent) => {
    e.preventDefault();
    if (loading) return;
    isHandSave.current = true;
    save();
  });
  // 自动保存
  // TODO: 自动保存最好不要有保存成功的提示
  useDebounceEffect(
    () => {
      isHandSave.current = false;
      save();
    },
    [componentList, pageInfo],
    { wait: 1000 }
  );

  return (
    <Button onClick={saveInfo} loading={loading}>
      保存
    </Button>
  );
};
// 发布按钮
const PublishButton: FC = () => {
  const nav = useNavigate();
  const { componentList } = useGetComponentInfo();
  const pageInfo = useGetPageInfo();
  const { id } = useParams();

  const { loading, run: publish } = useRequest(
    async () => {
      if (!id) return;
      await updateQuestionService(id, {
        ...pageInfo,
        componentList,
        isPublished: true, // 标志问卷已被发布
      });
    },
    {
      manual: true,
      onSuccess() {
        message.success("发布成功");
        nav(`/question/stat/${id}`);
      },
    }
  );

  return (
    <Button type="primary" loading={loading} onClick={publish}>
      发布
    </Button>
  );
};

const EditHeader: FC = () => {
  const nav = useNavigate();

  return (
    <div className={styles["header-wrapper"]}>
      <div className={styles.header}>
        <div className={styles.left}>
          <Space align="center">
            <Button type="link" icon={<LeftOutlined />} onClick={() => nav(-1)}>
              返回
            </Button>
            <TitleElement />
          </Space>
        </div>
        <div className={styles.main}>
          <EditToolBar />
        </div>
        <div className={styles.right}>
          <Space>
            <SaveButton />
            <PublishButton />
          </Space>
        </div>
      </div>
    </div>
  );
};

export default EditHeader;
